/* eslint-disable no-useless-escape */
/* eslint-disable no-prototype-builtins */
import {
  GET_DEPARTMENT_TREE,
  GET_DEPT_ROOT,
  GET_DEPT_TREE,
  GET_PAGE_EMPLOYEE,
  GET_ROLE_LIST,
  GET_STAFF_LIST,
} from '@/components/WorkFlow/apis';

let STAFF_LIST = [];
let ROLE_LIST = [];
const toHump = name => name.replace( /\_(\w)/g, function ( all, letter ) {
  return letter.toUpperCase();
} );
// 需要自行设置nodeID  重要！！！
async function getDepChildNode ( orgId ) {
  const promises = [GET_DEPT_TREE( { orgId } )];
  let res = [];
  // loadUser && promises.push( GET_USER_BY_DEPT( { deptId: orgId } ) )
  try {
    res = await Promise.all( promises );
  } catch ( error ) {/* this.$message.error('获取子节点数据出错')*/ }
  const nodes = res.reduce( ( p, c ) => {
    return [...p, ...c.data];
  }, [] );
  return nodes;
}
// 需要返回一个promise
async function loadDepOrUser ( node, loadDep = true ) {
  let nodeData = [];
  if ( node.level === 0 ) { // 根目录
    const test = await getRootDept();  // 获取根节点
    nodeData = [test];
  } else if ( node.level === 1 ) {
    nodeData = await getDepChildNode( node.data.deptId );  // 获取部门节点
  } else if ( !loadDep && node.level === 2 ) {
    nodeData = ( await GET_PAGE_EMPLOYEE() ).data;  // 获取部门下人员
  }
  return nodeData;
}
//获取角色列表
async function getRoleTree (node) {
  if (node.data && node.data.id) {
    return [];
  }
  let data = (await GET_ROLE_LIST({pageIndex: 1, pageSize: 1000, status: 10})).data.list;
  ROLE_LIST = data;
  let array = [];
  if (data) {
    data.map((item) => {
      let newItem = item;
      newItem.nodeId = item.id;
      newItem.roleId = item.id;
      array.push(newItem);
    });
  }
  return array;
}

// 获取指定人员和部门树
// 需要返回一个promise
async function getDeptUserTree ( node, loadDep = true ) {
  let nodeData = [];
  const staffList = (await GET_STAFF_LIST({pageIndex: 1, pageSize: 1000})).data.list;
  STAFF_LIST = staffList;
  const departmentTree = (await GET_DEPARTMENT_TREE()).data.list;
  nodeData = generateDeptUserTree(staffList, departmentTree, {
    labelKey: 'name',
    valueKey: 'id',
    childrenKey: 'childs',
    idKey: 'id',
    nameKey: 'name',
    relateKey: 'departmentId'
  });
  let data = [];
  if (node.data) {
    let id = node.data.id;
    data = getFromTreeById(id, nodeData);
    return data;
  }
  return nodeData;

}
function getFromTreeById(id, tree) {
  let item = null;
  return _rec(id, tree);
  function _rec(id, treeData) {
    if (treeData && treeData.length > 0) {
      for (let i in treeData) {
        if (treeData[i].id == id) {
          item = treeData[i].childs || [];
          break;
        }
        if (treeData[i].childs && treeData[i].childs.length > 0) {
          treeData[i].childs = _rec(id, treeData[i].childs);
        }
      }
    }
    return item;
  }
}
function generateDeptUserTree(staffList, departmentTree, opt) {
  let label = opt && opt.labelKey ? opt.labelKey : 'label';
  let value = opt && opt.valueKey ? opt.valueKey : 'value';
  let children = opt && opt.childrenKey ? opt.childrenKey : 'value';
  let listId = opt && opt.idKey ? opt.idKey : 'id';
  let listName = opt && opt.nameKey ? opt.nameKey : 'name';
  let listRelate = opt && opt.relateKey ? opt.relateKey : 'departmentId';
  let newOpt = {labelKey: label, childrenKey: children, valueKey: value, idKey: listId, nameKey: listName, relateKey: listRelate};
  return _rec(staffList, departmentTree, newOpt);
  function _rec (list, treeData, option) {
    for (let i = 0; i < treeData.length; i ++) {
      treeData[i].nodeId = treeData[i][option.valueKey];
      if (list && list.length > 0) {
        for (let j in list) {
          let item = list[j];
          if (!treeData[i]._isLeaf && item[option.relateKey] == treeData[i][option.valueKey]) {
            if (treeData[i][option.childrenKey] === undefined || !treeData[i][option.childrenKey]) {
              treeData[i][option.childrenKey] = [];
            }
            let staffRow = {};
            staffRow[option.labelKey] = item[option.nameKey];
            staffRow[option.valueKey] = treeData[i][option.valueKey].toString() + '-' + item[option.idKey].toString();
            staffRow.nodeId = staffRow[option.valueKey];
            staffRow._isLeaf = true;
            staffRow._id = item[option.idKey];
            staffRow.userId = item[option.idKey];
            treeData[i][option.childrenKey].push(staffRow);
          }
        }
      }
      if (treeData[i][option.childrenKey] && treeData[i][option.childrenKey].length > 0) {
        treeData[i][option.childrenKey] = _rec(list, treeData[i][option.childrenKey], option);
      }
    }
    return treeData;
  }
}


// 获取组织结构根节点
// 需要自行设置nodeID  重要！！！
async function getRootDept () {
  let res = [];
  try {
    res = ( await GET_DEPT_ROOT() ).data;
  } catch ( err ) {
    console.log(err);
  }
  return res;
}

function loadDepData ( node ) {
  return loadDepOrUser( node ); // 返回的promise
}

function loadUserData ( node ) {
  return getDeptUserTree( node, false );  // 返回的promise
}
function loadRoleData ( node ) {
  return getRoleTree( node);  // 返回的promise
}

async function searchRole (searchString, resolve, reject ) {
  resolve( ROLE_LIST.filter((item) => {
    return item.name.indexOf(searchString) > -1;
  }));
}
function searchRoleResTip (data) {
  return '';
}
function isRoleLeaf(data, node) {
  return true;
}
function isUserLeaf(data, node) {
  return data._isLeaf;
}

const defaultOption = {
  tabName: '部门',  // 选项卡名称
  tabKey: 'dep', //选项卡键值 传入的selected要和键值保持一致 eg: {dep: [], role: []}
  children: 'children', // 子节点标志
  // 生成每个节点的id 保证唯一
  nodeId: function ( data ) {
    return data.hasOwnProperty( 'userId' ) ? data.userId : data.deptId;
  },
  // 生成节点的名称 可选值 string | function
  label: function ( data, node ) {
    return data.hasOwnProperty( 'userId' ) ? data.userName : data.deptName;
  },
  // 判断是否为叶子节点 可选值 string | function
  isLeaf: function ( data, node ) {
    return data.hasOwnProperty( 'userId' ); // 含有empID为人员  且为叶子节点
  },
  // 搜索后的结果如果需要展示一些提示文字 例如搜索人员 提示人员所属部门  可以使用该属性
  // function
  searchResTip: function ( data ) {
    return '部门：' + data.departmentName;
  },
  // 判断该节点是否可选 例如同时选择部门和部门下的人
  disabled: function ( data, node ) {
    return false;
  },
  // 动态请求后台拿到节点数据 返回一个promise
  onload: loadDepData,
  // 搜索节点方法
  onsearch: async function ( searchString, resolve, reject ) {
    // const param = { page: 1, limit: 200, searchName: searchString }
    resolve( STAFF_LIST.filter((item) => {
      return item.name.indexOf(searchString) > -1;
    }));
  }
};

export const DEP_CONFIG = Object.assign( {}, defaultOption );
export const ROLE_CONFIG = Object.assign( {}, defaultOption, { tabKey: 'role', tabName: '角色', onload: loadRoleData, label: 'name', children: 'children', onsearch: searchRole, isLeaf: isRoleLeaf, searchResTip: searchRoleResTip } );
export const USER_CONFIG = Object.assign( {}, defaultOption, { tabKey: 'user', tabName: '指定人员', onload: loadUserData, disabled: ( data, node ) => !data._isLeaf, label: 'name', isLeaf: isUserLeaf } );
const DEP_USER_CONFIG = Object.assign( {}, defaultOption, { tabKey: 'dep&user', tabName: '部门和人员', onload: loadUserData, disabled: () => false } );
const POSITION_CONFIG = Object.assign( {}, defaultOption, { tabKey: 'position', tabName: '岗位' } );
export const CONFIG_LIST = [DEP_CONFIG, ROLE_CONFIG, USER_CONFIG, DEP_USER_CONFIG, POSITION_CONFIG];
